package co.unipiloto.identify.camera;

import java.io.IOException;

import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.provider.MediaStore.Images.Media;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CustomCameraView extends SurfaceView
{
	//atributos
	private boolean isPreviewRunning=false;
	
	public  Camera camera;
   public Camera getCamera() {
		return camera;
	}



	public void setCamera(Camera camera) {
		this.camera = camera;
	}


	private SurfaceHolder previewHolder;
   
   
   private float direction;//
	
	public static SensorManager sensorMan;
	
   public CustomCameraView(Context ctx)
   {
	   super(ctx);
	   
	   sensorMan = (SensorManager)ctx.getSystemService(Context.SENSOR_SERVICE);
	      sensorMan.registerListener(
	         listener, 
	         sensorMan.getDefaultSensor(
	            SensorManager.SENSOR_ORIENTATION), 
	         SensorManager.SENSOR_DELAY_FASTEST);
	      
	   previewHolder = this.getHolder();
	         previewHolder.setType 
	           (SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	         previewHolder.addCallback(surfaceHolderListener);
   }
   
   
   SurfaceHolder.Callback surfaceHolderListener = new SurfaceHolder.Callback() {
	      public void surfaceCreated(SurfaceHolder holder) {
	            camera=Camera.open();

	            try {
	                    camera.setPreviewDisplay(previewHolder);
	            }
	            catch (Throwable t){ }
	           }
	   public void surfaceChanged(SurfaceHolder holder, int format, int w,
	         int h)
	   {
		   if (isPreviewRunning) {
	            camera.stopPreview();
	        }
	        Camera.Parameters p = camera.getParameters();
	        p.setPreviewSize(w, h);
	        camera.setParameters(p);
	        try {
				camera.setPreviewDisplay(holder);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        camera.startPreview();
	        isPreviewRunning = true;
	   }

	   public void surfaceDestroyed(SurfaceHolder arg0)
	   {
		   isPreviewRunning = false;
	      camera.stopPreview();
	      camera.release();   
	   }
	 };
	 
	 

		SensorEventListener listener = new SensorEventListener(){

			@Override
			public void onAccuracyChanged(Sensor arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSensorChanged(SensorEvent evt) {
				 float vals[] = evt.values;   
			      direction = vals[0];
				
			}
			};
}